﻿package net.wangit.dev.tree;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.DomainAction;
import net.wangit.dev.LockUtil;
import net.wangit.dev.VersionUtil;
import net.wangit.dev.version.TreeVersion;
import net.wangit.dev.version.Version;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
import net.wangit.view.tree.TreeCache;
import net.wangit.view.tree.TreeConfigCache;


public class SaveTreeAction extends DomainAction {

	private static Version version = new TreeVersion();

	public SaveTreeAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String newTreeId = ac.getRequestParameter("t.tid");
		if (!Checker.isEmpty(newTreeId))
			newTreeId = StringUtil.clearSpace(newTreeId.toLowerCase());
		format(ac, newTreeId);
		super.doAction(db, ac);
		ac.setSessionAttribute(TreeUI.KEY, newTreeId);
		String oldTreeId = ac.getRequestParameter("t.tid.k");
		if (!Checker.isEmpty(oldTreeId) && oldTreeId.equals(newTreeId))
			ac.getActionResult().setScript(null);
		TreeCache.clear(domain, oldTreeId);
		TreeConfigCache.clear(domain, oldTreeId);
		TreeReferenceUtil.update(db, domain, oldTreeId, newTreeId);
		VersionUtil.saveVersion(ac, version, domain, newTreeId);
	}

	private void format(ActionContext ac, String treeId) {
		List<Table> tables = ac.getTables();
		for (int i = 0; i < tables.size(); i++) {
			Table table = tables.get(i);
			if ("TREECONFIG".equals(table.getTableName()))
				formatConfig(ac, table.getRows(), treeId);
			else if ("TREE".equals(table.getTableName()))
				formatTree(table.getRows(), treeId);
		}

	}

	private void formatConfig(ActionContext ac, List<ColumnRow> rows,
			String treeId) {
		if (rows.size() > 0) {
			ColumnRow row = rows.get(0);
			row.set("tid", treeId);
			LockUtil.setFields(ac, row, "tc");
		}
	}

	private void formatTree(List<ColumnRow> rows, String treeId) {
		for (int i = 0; i < rows.size(); i++) {
			ColumnRow row = rows.get(i);
			row.set("tid", treeId);
			String id = row.get("id");
			if (!Checker.isEmpty(id)) {
				id = StringUtil.clearSpace(id.toLowerCase());
				row.set("id", id);
			}
			String parentId = row.get("pid");
			if (!Checker.isEmpty(parentId)) {
				parentId = StringUtil.clearSpace(parentId.toLowerCase());
				row.set("pid", parentId);
			}
		}

	}

}
